<template>
	<view>
		<view class="form">
			<view class="form-item">
				<view class="form-title require">课程名称</view>
				<input class="input-item" v-model="form.title"/>
			</view>
			
			<view class="form-item" @click="changePrColumns(cache.menu, 'text', 'menuPr')">
				<view class="form-title">课程类型</view>
				<view class="input-item">{{ form.menuPr }}</view>
			</view>
			
			<view class="form-item">
				<view class="form-title">老师照片</view>
				
				<view class="input-item">

					<image :src="form.picture" mode="aspectFill" style="width: 150rpx;height: 150rpx;border-radius: 8rpx;"></image>
				</view>
			</view>
			
			<view class="form-item" @click="changePrColumns(cache.teacher, 'name', 'teacher')">
				<view class="form-title">上课老师</view>
				<view class="input-item">{{ form.teacher }}</view>
			</view>
			
			<view class="form-item">
				<view class="form-title">课程难度</view>
				<view class="input-item">
					<view style="float: right;">
						<u-rate	:count="5" v-model="form.difficulty" size="40" gutter="20"></u-rate>
					</view>
				</view>
			</view>
			
			<view class="form-item">
				<view class="form-title">人数限制</view>
				<view class="input-item">
					<view style="float: right;">
						<u-number-box v-model="form.maxMan" buttonSize="40" inputWidth="100" integer>
							<view slot="minus" class="minus">
								<u-icon name="minus" size="30"></u-icon>
							</view>
							<text slot="input" style="width: 50px;text-align: center;" class="input">
								{{form.maxMan}} 
							</text>
							<view slot="plus" class="plus">
								<u-icon name="plus" size="30"></u-icon>
							</view>
						</u-number-box>
					</view>
				</view>
			</view>
			
			<view class="form-item">
				<view class="form-title">备注</view>
				<input class="input-item" v-model="form.other"/>
			</view>
			
			<m-switch v-model="mSwitch.flag" @mClick="changeMSwitch"></m-switch>

			<view class="form-item" @click="changeDatetimePrModel('sTime')">
				<view class="form-title require">上课时间</view>
				<view class="input-item">{{ form.sTime }}</view>
			</view>
			
			<view class="form-item" @click="changeDatetimePrModel('eTime')">
				<view class="form-title require">下课时间</view>
				<view class="input-item">{{ form.eTime }}</view>
			</view>
			
			<view class="from-btn-view">
				<view @click="formConfirm" class="from-btn-confirm">确认</view>
			</view>

			<u-picker :show='picker.show' :columns='picker.columns' 
				itemHeight='100' 
				ref="pr"
				@confirm="prConfirm" 
				@cancel="prClose">
			</u-picker>	
			
			<u-datetime-picker
				:show="datetimePicker.show"
				v-model="datetimePicker.value"
				:mode="datetimePicker.mode" 
				itemHeight="100"
				:formatter="formatter"
				ref="datetimePr"
				@confirm="datetimePrConfirm"
				@cancel="datetimePrClose">
			></u-datetime-picker>
		</view>
	</view>
</template>

<script>
	import mSwitch  from'@/component/m-Switch/m-Switch.vue'
	
	const lessonCloud = uniCloud.importObject('lesson')
	const menuCloud = uniCloud.importObject('menu')
	const teacherCloud = uniCloud.importObject('teacher')
	export default {
		components: { mSwitch },
		data() {
			return {
				form: {					
					title: '',
					menuPr: '',
					picture: '',
					teacher: '',
					difficulty: 3,
					sTime: '',
					eTime: '',
					maxMan: 3,
					other: '',
				},
				mSwitch: {
					flag: true
				},
				picker: {
					show: false,
					columns: [[]],
					currentObj: ''
				},
				datetimePicker: {
					show: false,
					value:  `${new Date().getHours()}:${new Date().getMinutes()}`,
					mode: 'time',
					currentObj: ''
				},
				cache: {
					menu: [],
					teacher: []
				},
				confirming: false
			}
		},
		methods: {
			init() {
				this.getMenu()
				this.getTeacher()
			},
			getMenu() {
				menuCloud.get().then(({data}) => {
					this.cache.menu = data
					this.form.menuPr = data[0].text
				})
			},
			getTeacher() {
				teacherCloud.getTeacher().then(({data}) => {
					this.cache.teacher = data
					this.form.teacher = data[0].name
					teacherCloud.getTeacherByName(data[0].name).then(({data}) => {
						this.form.picture = data[0].picture
					})
				})
			},
			/**
			 * @method 将数据存入Picker中
			 * @param {Object} from 数据源
			 * @param {String} fromColumns 数据源内的字段（一级子字段）
			 * @param {String} to 目标字段
			 */
			changePrColumns(from, fromColumns, to) { 
				const col = [[]]
				for (let item of from) {
					col[0].push(item[fromColumns])
				}
				this.picker = {
					show: true,
					columns: col,
					currentObj: to
				}
			},
			/**
			 * @method Picker确认事件
			 * @param {String} arg0 目标字段
			 * @param {Object} event $event事件
			 */
			prConfirm({value}) {
				this.form[this.picker.currentObj] = value[0]
				
				if (this.picker.currentObj === 'teacher') {
					teacherCloud.getTeacherByName(this.form.teacher).then(({data}) => {
						this.form.picture = data[0].picture
					})
				}
				
				this.prClose()
			},
			/**
			 * @method Picker关闭事件
			 */
			prClose() {
				this.picker.show = false
			},
			changeMSwitch(flag) {
				this.mSwitch.flag = flag
				this.form.sTime = ''
				this.form.eTime = ''
				
				if (flag) {
					this.datetimePicker.value = `${new Date().getHours()}:${new Date().getMinutes()}`
					this.datetimePicker.mode = 'time'
				} else {
					this.datetimePicker.value = Number(new Date())
					this.datetimePicker.mode = 'datetime'
				}
			},
			changeDatetimePrModel(obj) {
				this.datetimePicker.show = true
				this.datetimePicker.currentObj = obj
			},
			datetimePrConfirm({value}) {
				if (this.datetimePicker.mode === 'datetime') {
					const dateObj = new Date(value)
					const year = dateObj.getFullYear()
					const month = correct(dateObj.getMonth() + 1) 		
					const day = correct(dateObj.getDay())
					const hour = correct(dateObj.getHours())
					const minute = correct(dateObj.getMinutes())
					function correct(arg) { // 个位加个0在前面
						return arg < 10 ? '0' + arg : arg 
					}
					
					this.form[this.datetimePicker.currentObj] = `${year}-${month}-${day} ${hour}:${minute}`
				} else if (this.datetimePicker.mode === 'time') {
					this.form[this.datetimePicker.currentObj] = value
				}

				this.datetimePrClose()
			},
			datetimePrClose(){
				this.datetimePicker.show = false
			},
			validForm() {
				const ignore = ['other', 'picture']
				
				for (let item in this.form) {
					if (ignore.indexOf(item) !== -1) {
						continue
					}
					
					if (this.form[item] === '') {
						return false
					}
				}
				return true
			},
			formObjToDbObj() {
				const {menuPr, ...confirm} = this.form
				if (this.datetimePicker.mode === 'time') {
					confirm.sTime = '0000-00-00 ' + this.form.sTime 
					confirm.eTime = '0000-00-00 ' + this.form.eTime 
				}
				for (let item of this.cache.menu) {
					if (item.text === this.form.menuPr) {
						confirm.status = item.status
						break
					}
				}
				return confirm
			},
			formConfirm() {
				if (this.confirming) {
					uni.showToast({
						icon: 'none',
						title: '请勿频繁操作'
					})
					return
				}
				this.confirming = true

				if (!this.validForm()) {
					uni.showToast({
						icon: 'none',
						title: '必填项为空'
					})
					return 
				}
				
				const confirm =  this.formObjToDbObj()
				lessonCloud.add(confirm).then(({id}) => {
					if (id) {
						uni.showToast({
							icon: 'success',
							title: '添加成功',
							success() {
								setTimeout(() => {
									uni.switchTab({
										url: '/pages/lesson/lesson'
									})
								}, 500)
							}
						})
					} else {
						uni.showToast({
							icon: 'none',
							title: '服务器异常'
						})
					}
				})
				
				setTimeout(() => {
					this.confirming = false
				}, 3000)
			},

			formatter(type, value) {
				switch (type) {
					case 'year': return `${value}年`
					case 'month': return `${value}月`
					case 'day': return `${value}日`
					case 'hour': return `${value}时`
					case 'minute': return `${value}分`
					default: return value
 				}
			}
		},
		onReady() {
			this.$refs.datetimePr.setFormatter(this.formatter)
		},
		created() {
			this.init()	
		},
	}
</script>
 
<style lang="scss">
	.form{
		padding: 20rpx;
	}
	
	.form-item{
		margin: 20rpx;
		padding: 20rpx;
		background-color: #F7F8F8;
		display: flex;
		justify-content: space-around;
		align-items: center;
		border-radius: 20rpx;
	}
	
	.form-title{
		text-align: center;
		font-weight: 700;
	}	
	
	.input-item{
		width: 450rpx;
		text-align: right;
	}
	
	.from-btn-view{
		margin: 50rpx 20rpx;
		
		.from-btn-confirm{
			background-color: #1A73E8;
			color: #fff;
			display: flex;
			justify-content: center;
			align-items: center;
			border-radius: 20rpx;
			height: 70rpx;
		}
	}
	
	.require::after{
		content: '*';
		color: red;
		margin-left: 3rpx;
	}
</style>

	<!-- 			
		HTML
					<uni-file-picker v-model="form.picture"
						fileMediatype="image"
						file-extname='png,jpg'
						:auto-upload="false"
						limit='1' class="file"
						ref='filePr' @select="fileSelect">
					</uni-file-picker>	 
					
		CSS
				.file{
					/deep/ .uni-file-picker__container{
						flex-direction: row-reverse;
					}
					
					/deep/ .file-picker__box{
						min-width: 200rpx;
						min-height: 200rpx;
					}
				}
					
					
		JS
					 /**
					  * @method 图片选择事件
					  */
					fileSelect({tempFiles}) {
						const file = tempFiles[0]
						// 小于2M
						if (file.size > 2000000) {
							this.$refs.filePr.clearFiles()
							uni.showToast({
								icon: 'none',
								title: '图片必须小于 2M'
							})
						}
					}
					
					
					// this.$refs.filePr.upload().then(res => {
					// 	confirm.picture = res[0]?.url
					// })
	-->
					
					
